import configparser
import os
import pymysql

class ConfigReader:
    def __init__(self):
        self.config = configparser.ConfigParser()
        config_path = os.path.join(os.path.dirname(__file__), 'config.ini')
        if not os.path.exists(config_path):
            raise FileNotFoundError(f"配置文件 {config_path} 不存在")
        self.config.read(config_path)

    def get_cursor(self):
        try:
            conn = pymysql.connect(
                host=self.config.get('database', 'host'),
                port=self.config.getint('database', 'port'),
                user=self.config.get('database', 'user'),
                password=self.config.get('database', 'password'),
                database=self.config.get('database', 'dbname')
            )
            return conn.cursor()
        except Exception as e:
            print(f"数据库连接失败: {e}")
            return None

if __name__ == "__main__":
    try:
        reader = ConfigReader()
        cursor = reader.get_cursor()
        if cursor:
            print("成功获取数据库游标")
    except FileNotFoundError as e:
        print(e)